//
//  SBMenuController.m
//  MailNotify
//
//  Created by Luke van der Hoeven on 5/14/08.
//  Copyright 2008 Cedarville University. All rights reserved.
//

#import "SBMenuController.h"

@implementation SBMenuController

- (void)awakeFromNib {
	NSTimer *timer;
	mail = [SBApplication applicationWithBundleIdentifier:@"com.apple.mail"];
	
	unreadMessages = [[MailArray alloc] init];
	
	NSStatusBar *bar = [NSStatusBar systemStatusBar];
	
    theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
    [theItem retain];
	
	NSString *path = [[NSBundle mainBundle] pathForResource:@"Picasso 2" ofType:@"icns"]; 
	NSImage *image = [[NSImage alloc] initWithContentsOfFile: path];
	
	NSSize size = NSMakeSize(16.0, 16.0);
	[image setSize:size];
	
	[self updateMailItems];
	
	[theItem setImage:image];
    [theItem setHighlightMode:YES];
    [theItem setMenu:sbMenu];
	
	if (self) {
		timer = [NSTimer scheduledTimerWithTimeInterval:10
												 target:self 
											   selector:@selector(updateMailItems) 
											   userInfo:nil 
												repeats:YES];
	}
}

- (void)updateMailItems {
	int newCount = [[mail inbox] unreadCount];
	NSString *temp = [NSString stringWithFormat:@"%d", newCount];
	[theItem setTitle:temp];
	
	NSArray *messages = [[[mail inbox] messages] get];
	for(MailMessage *msg in messages) {
		if(![msg readStatus] && ![unreadMessages isAdded:[msg id]]) {
			[sbMenu addItemWithTitle:[msg subject] action:@selector(openMessage:) keyEquivalent:@""];
			[unreadMessages add:[msg id] obj:msg];
		} else if([unreadMessages isAdded:[msg id]]) {
			[unreadMessages remove:[msg id]];
			[self refreshList];
		}
	}
}

- (IBAction)openMessage:(id)sender {

}

- (void)refreshList {
	for(NSMenuItem *mi in [sbMenu itemArray]) {
		if(![unreadMessages hasTitle:[mi title]] && ![mi isSeparatorItem] && ![mi isEnabled]) {
			[sbMenu removeItem:mi];
		}
	}
}

- (IBAction)openMail:(id)sender {
	[mail activate];
	[mail release];
}

@end
